package com.w.contro;

import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.w.domain.Gly;
import com.w.domain.IpAndAddress;
import com.w.domain.User;
import com.w.domain.WenJian;
import com.w.service.impl.UserServiceImpl;
import com.w.util.GetAddressByIpUtil;
import com.w.util.IpUtil;
import com.w.util.MailUtil;
import com.w.util.UUIDUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.*;


@Slf4j
//@RestController 相当于@Controller，@ResponseBody
@Controller

public class contro {

    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private MailUtil mailUtil;

    @Value("${file.uploadurl}")
    private String uploadPath;

    /**
     * 获取ip和通过IP查询的地址
     * @param request
     * @return
     */
    @RequestMapping(value = "/ipAndAddress", method = RequestMethod.GET)
    @ResponseBody
    public IpAndAddress test(HttpServletRequest request){
        //获取IP地址
        String ipAddress = IpUtil.getIpAddr(request);
        String cityInfo = GetAddressByIpUtil.getCityInfo(ipAddress);
        Long fwl = userService.selectFwl();
        fwl++;//每次点击进入网站首页访问量+1
        userService.updataFwl(fwl);

        IpAndAddress ipAndAddress = new IpAndAddress();
        ipAndAddress.setIp(ipAddress);
        ipAndAddress.setAddress(cityInfo);
        ipAndAddress.setFwl(fwl);
        return ipAndAddress;
    }

    @RequestMapping(value = "/lyb.html")
    public String index(){
        return "lyb";
    }

    @RequestMapping(value = {"/","/home.html"})//进入项目直接访问新年祝福页面
    public String ind(){
        return "home";
    }
    //使之经过前端控制器
    @RequestMapping("/wall.html")
    public String getWall(){
        return "wall";
    }

    /**
     * 获取所有留言
     * @param model
     * @param pageNum
     * @param pageSize
     * @return
     */
    @RequestMapping("/getAll")
    public String getAllInfo(Model model, @RequestParam(value = "pageNum", defaultValue = "0") int pageNum, @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
        PageInfo<User> pageInfo = userService.getAllInfo(pageNum,pageSize);
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("users",pageInfo.getList());
        return "Ican";
    }

    @RequestMapping("/queryByLei")
    @ResponseBody
    public String getSongInfo(@RequestParam(value = "name", defaultValue = "默认") String name,@RequestParam(value = "pageNum", defaultValue = "0") int pageNum,
                              @RequestParam(value = "pageSize", defaultValue = "10") int pageSize){
        PageInfo<WenJian> pageInfo = userService.getAllWenjian(name,pageNum,pageSize);

        String s = JSONObject.toJSONString(pageInfo);

        return s;
    }

    @RequestMapping("/queryByName")
    public ModelAndView getAllWenjian(@RequestParam(value = "name", defaultValue = "姓名") String name,@RequestParam(value = "pageNum", defaultValue = "0") int pageNum,
                               @RequestParam(value = "pageSize", defaultValue = "10") int pageSize){
        ModelAndView modelAndView = new ModelAndView();
        PageInfo<WenJian> pageInfo = userService.getAllWenjian(name,pageNum,pageSize);

        modelAndView.addObject("pageInfo", pageInfo);

        modelAndView.addObject("wenjians",pageInfo.getList());
        modelAndView.addObject("name1",name);
        if (pageInfo.getList().isEmpty()){
            modelAndView.addObject("msg","没有此用户文件");
            modelAndView.setViewName("wall");
            return  modelAndView;
        }

      modelAndView.setViewName("wenjian");
        return modelAndView;
    }

    /**
     * 插入一条留言
     * @param user
     * @param request
     * @param session
     * @return
     */
    @RequestMapping("/insert")
    public String insertInfo(User user, HttpServletRequest request, HttpSession session){
        Date date = new Date();
        Timestamp timestamp = new Timestamp(date.getTime());
        String ipAddress = IpUtil.getIpAddr(request);
        String cityInfo = GetAddressByIpUtil.getCityInfo(ipAddress);

        user.setIp(ipAddress);
        user.setData(timestamp);

        user.setAddress(cityInfo);
        userService.insertInfo(user);

        return "redirect:/getAll";//使用重定向防止表单重复提交
    }

    @RequestMapping("/glyLogin.html")
    public String getGly(){
        return "glyLogin";
    }
    /**
     * 管理员登陆
     */
    @RequestMapping("glylogin")
    public ModelAndView glyLogin(Gly gly){
        ModelAndView modelAndView = new ModelAndView();
        Gly gly1 =  userService.glyLogin(gly);
        if(gly1==null){

            modelAndView.addObject("msg", "用户名或密码错误");
            modelAndView.setViewName("glyLogin");
        }else {
            modelAndView.addObject("msg", gly1.getUsername());
            modelAndView.setViewName("gly");

        }
        return modelAndView;
    }
    /**
     * 管理员删除留言
     * @param ip
     * @return
     */
    @RequestMapping("delete")
    public ModelAndView deleteInfo(@Param("ip") String ip){
        ModelAndView modelAndView = new ModelAndView();

       int i = userService.deleteInfo(ip);

        if(i>0){
            modelAndView.addObject("msg", "删除"+ip+"成功");
            modelAndView.setViewName("gly");
        }else{
            modelAndView.addObject("msg", "失败了！！！");
            modelAndView.setViewName("gly");
        }
        return modelAndView;
    }

    @RequestMapping("deleteOne")
    public ModelAndView deleteOne(Integer wid){
        ModelAndView modelAndView = new ModelAndView();
        WenJian wenJian = userService.getOneWenjian(wid);
        boolean b = deleteServerFile(wenJian.getAddress(), wenJian.getUuidName());
        int i = userService.deleteOne(wid);
        if(i>0 && b == true){
            modelAndView.addObject("msg", "删除"+"成功");
            modelAndView.setViewName("wall");
        }else{
            modelAndView.addObject("msg", "失败了！！！");
            modelAndView.setViewName("wall");
        }
        return modelAndView;
    }

    public  boolean deleteServerFile(String filePath, String fileName){
        boolean deleteFlag = false;
        File file = new File(filePath + fileName);
        if (file.exists() && file.isFile() && file.delete()){
            deleteFlag = true;
        }
        else{
            deleteFlag = false;
        }
        return deleteFlag;
    }

    /**
     * 新年祝福话语
     * 用于首页展示
     * @return
     */
    @RequestMapping("/happyInfo")
    @ResponseBody
    public String yearInfo(){
        Random random = new Random();
        int id = random.nextInt(20)+1;
        return userService.getHappyInfo(id);
    }

    /**
     * 新年祝福相关
     * 发送新年祝福邮件
     * @param mail
     * @param request
     * @return
     */
    @RequestMapping("/mail")
    public String mailInfo(String mail, HttpServletRequest request){

        Random random = new Random();
        int id = random.nextInt(20)+1;
        String happyInfo = userService.getHappyInfo(id);

        String ipAddress = IpUtil.getIpAddr(request);
        String cityInfo = GetAddressByIpUtil.getCityInfo(ipAddress);
        log.info(ipAddress);
        log.info(cityInfo);
        Date date = new Date();
        Timestamp timestamp = new Timestamp(date.getTime());

        Map<String, Object> valueMap = new HashMap<String, Object>();
        valueMap.put("ipAddress",ipAddress);
        valueMap.put("cityInfo",cityInfo);
        valueMap.put("to", mail );
        valueMap.put("title", "新年祝福邮件");
        valueMap.put("content",happyInfo);
        valueMap.put("happyInfo",happyInfo);
        valueMap.put("timestamp",timestamp);

        mailUtil.sendSimpleMail(valueMap);

        return "redirect:https://mail.qq.com/";
    }

    /**
     * MultipartFile 自动封装上传过来的文件

     * @return
     */
    @PostMapping("/upload")
    public ModelAndView upload(HttpServletRequest request,@RequestPart("file") MultipartFile file,
                         @RequestPart("files") MultipartFile[] files, WenJian wenJian) throws IOException {
        ModelAndView modelAndView = new ModelAndView();
        log.info("上传的信息，headerImg={}，photos={},wenjian={}"
                ,file.getSize(),files.length,wenJian.toString());
        int a = 1;
        if(!file.isEmpty()){
            //保存到文件服务器，OSS服务器
           a = setImageInfo(request,file,wenJian);

        }

        if(files.length > 0){
            for (MultipartFile file1 : files) {
                if(!file1.isEmpty()){
                  a =  setImageInfo(request,file1,wenJian);

                }
            }
        }
        if (a==1){
            modelAndView.addObject("msg","上传成功！");
        }else{
            modelAndView.addObject("msg","上传失败！");
        }

        modelAndView.setViewName("wall");
        return modelAndView;
    }

    public int setImageInfo(HttpServletRequest request, MultipartFile file,WenJian wenJian) throws IOException {
        //物品图片信息
        String path ;
        String type ;
        String avator;
        if(!file.isEmpty()) {
            String fileName = file.getOriginalFilename();
            wenJian.setWenName(fileName);
            wenJian.setAddress(uploadPath);

            wenJian.setSize(getSize(file.getSize()));
            wenJian.setDate(new DateTime());
            type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1) : null;
            if (type != null) {
                // 自定义的文件名称
                Calendar rightNow=Calendar.getInstance();
                Integer year = rightNow.get(Calendar.YEAR);
                Integer month = rightNow.get(Calendar.MONTH)+1; //第一个月从0开始，所以得到月份＋1
                Integer day = rightNow.get(Calendar.DAY_OF_MONTH);

                String date=year+""+month+""+day;
                String trueFileName = UUIDUtils.getUUID()+date+"."+type;
                wenJian.setUuidName(trueFileName);
                // 设置存放图片文件的路径
                path = uploadPath +trueFileName;
                //判断文件父目录是否存在
                File dest=new File(path);
                if(!dest.getParentFile().exists()){
                    dest.getParentFile().mkdir();
                }
                //保存文件
                log.info(330+path);
                file.transferTo(new File(path));
                avator=request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/images/" + trueFileName;
                wenJian.setWenUrl(avator);
                log.info("数据库存放图片文件的路径:" + avator);
            }else {
                log.info("文件类型为空");
                return 0;
            }
        }else {
            log.info("没有找到相对应的文件");
            return 0;
        }

        //写入数据库
        int a = userService.insertWenjian(wenJian);
        return a;
    }
    public String getSize(Long size) {
        double s = (double) size;
        String unit;
        if (size != -1L) {
            int l;
            if (size < 1024L) {
                l = 0;
            } else if (size < 1024L * 1024L) {
                l = 1;
                s = (double) size / 1024L;
            } else {
                for (l = 2; size >= 1024L * 1024L; l++) {
                    size = size / 1024L;
                    if ((size / 1024L) < 1024L) {
                        s = (double) size / 1024L;
                        break;
                    }
                }
            }
            switch (l) {
                case 0:
                    unit = "Byte";
                    break;
                case 1:
                    unit = "KB";
                    break;
                case 2:
                    unit = "MB";
                    break;
                case 3:
                    unit = "GB";
                    break;
                case 4:
                    //不可能也不该达到的值
                    unit = "TB";
                    break;
                default:
                    //ER代表错误
                    unit = "ER";
            }

            String format = String.format("%.0f", s);
            return format + unit;
        }
        return null;
    }


}
